#!/usr/bin/python
# -*- coding: utf-8 -*-
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation; either version 3, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTIBILITY
# or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.

#Pytigon - wxpython and django application framework

#author: "Slawomir Cholaj (slawomir.cholaj@gmail.com)"
#copyright: "Copyright (C) ????/2012 Slawomir Cholaj"
#license: "LGPL 3.0"
#version: "0.1a"

from base64 import b32encode, b32decode
from schlib.schtools import schjson
import sys
from schlib.schdjangoext.table import Table
from schlib.schfs.vfs import VfsManager, get_dir, open_file
from schlib.schfs.zip import VfsPluginZip
from schlib.schfs.sevenzip import VfsPluginSevenZip
from schlib.schfs.tar import VfsPluginTar
from schlib.schfs.vfstools import replace_dot
from django.http import HttpResponse
from django.core.cache import cache
from schlib.schtools.data import is_null
import datetime
import re
import traceback

vfsman = VfsManager()
vfsman.install_plugin(VfsPluginZip())
vfsman.install_plugin(VfsPluginSevenZip())
vfsman.install_plugin(VfsPluginTar())


def thread_fs(self, parm, fun):
    value = schjson.loads(parm)
    src_file = b32decode(value[0][0])
    src_files = []
    for pos in value[0][1]:
        src_files.append(b32decode(pos).split('/')[-1])
    selmask = value[0][2]
    key = value[0][3]
    src_path = b32decode(value[1][0])
    dest = b32decode(value[1][1])
    fun(
        self,
        src_path,
        dest,
        src_files,
        selmask,
        key,
        )


def thread_copy(self, parm):
    return thread_fs(self, parm, vfsman.copy)


def thread_move(self, parm):
    return thread_fs(self, parm, vfsman.move)


def thread_delete(self, parm):
    return thread_fs(self, parm, vfsman.delete)


scr = \
    """
import time
i=0
while True:
   time.sleep(1)
   print "TestThread:%s %s" % (self.getName(), i)
   x = { 'progress': i*5, 'description': 'count: %s' % i }
   #self.WriteInfo("TestThread:%s %s" % (self.getName(), i) )
   self.WriteInfo(x)
   i = i + 1
   if i>20:
       break
"""


def test_thread(self):
    import time
    i = 0
    while not self.exit:
        time.sleep(1)
        x = {'progress': i * 5, 'description': 'count: %s' % i}
        self.WriteInfo(x)
        x = {
            'progress': i * 5,
            'description': 'count: %s' % i,
            'template': 'schcommander/copyprogress.html',
            'exit': 0,
            }
        self.WriteData(x, False)
        i = i + 1
        if i > 20:
            break
    x = {
        'progress': 100,
        'description': 'Zadanie zako\xc5\x84czone',
        'template': 'schcommander/copyprogress.html',
        'exit': 1,
        }
    self.WriteData(x, False)


def str_cmp(x, y, ts):
    (id, znak) = ts[0]
    if x[id] > y[id]:
        return znak
    if x[id] < y[id]:
        return -1 * znak
    if len(ts) > 1:
        return str_cmp(x, y, ts[1:])
    else:
        return 0


class VfsTable(Table):

    def __init__(self, folder):
        self.var_count = -1
        self.Folder = replace_dot(folder).replace('%20', ' ')
        self.AutoCols = []
        self.ColLength = [10, 10, 10]
# self.ColNames = ["ID", "Nazwa", "Rozmiar", "Czas mod", "Czas otw", "Czas utw",
# "Wlasciciel", "Link"]
        self.ColNames = ['ID', 'Nazwa', 'Rozmiar', 'Czas utw']
        self.ColTypes = ['int', 'str', 'int', 'datetime']
        self.DefaultRec = ['', 0, None]

    def _size_to_color(self, size):
        colors = ((1024, '#fff'), (1048576, '#fdd'), (1073741824, '#f99,#FFF'),
                  (1099511627776, '#000,#FFF'))
        for pos in colors:
            if size < pos[0]:
                return pos[1]
        return colors[-1][1]

# fdd

    def _time_to_color(self, time):
        if time:
            d2 = datetime.datetime.strptime(time[:10], '%Y-%m-%d').date()
            size = (datetime.date.today() - d2).days
            colors = ((1, '#FFF,#F00'), (7, '#efe'), (31, '#dfd'), (365, '#cfc'
                      ), (365, '#000,#FFF'))
            for pos in colors:
                if size < pos[0]:
                    return pos[1]
            return colors[-1][1]
        else:
            return '#FFF,#F00'

    def _get_table(self, value=None):
        f = get_dir(self.Folder, vfsman)
        files = []
        if value:
            cmp = re.compile(value, re.IGNORECASE)
        else:
            cmp = None
        for pos in f.get_dirs():
            if cmp and cmp.match(pos.name) or not cmp:
                action = pos.id
                files.append([  #                    (pos.atime, ',#dfd'),
                                # (pos.mtime, ',#ddf'),
                                # pos.id,                    "",
                    pos.id,
                    (pos.name, ',#fdd'),
                    '',
                    (pos.ctime, ',,#f00,s'),
                    pos.param,
                    {'edit': ('tableurl', '../../%s//' % action,
                     'Zmie\xc5\x84 folder')},
                    ])
        action = b32encode(self.Folder.encode('utf-8'))
        f.get_files()
        for pos in f.get_files():
            if cmp and cmp.match(pos.name) or not cmp:
                files.append([  #                    pos.atime,
                                # pos.mtime,                    pos.islink,
                                # pos.uid,
                    pos.id,
                    pos.name,
                    (pos.size, '>,' + self._size_to_color(pos.size)),
                    (pos.ctime, ',' + self._time_to_color(pos.ctime)),
                    pos.param,
                    {'edit': ('command', '../../%s//' % pos.id,
                     'Otw\xc3\xb3rz plik')},
                    ])
        return files

    def page(
        self,
        nr,
        sort=None,
        value=None,
        ):
        #key = 'FOLDER_' + b32encode(self.Folder.encode('utf-8')) + '_TAB'

        key = 'FOLDER_' + b32encode(self.Folder.encode('utf-8')).decode('utf-8') + '_TAB'

        tabvalue = cache.get(key + '::' + is_null(value, ''))
        tabvalue = None
        if tabvalue:
            tab = tabvalue
        else:
            tab = self._get_table(value)[nr * 256:(nr + 1) * 256]
            cache.set(key + '::' + is_null(value, ''), tab, 300)
        self.var_count = len(tab)
        if sort != None:
            s = sort.split(',')
            ts = []
            for pos in s:
                if pos != '':
                    id = 0
                    znak = 0
                    if pos[0] == '-':
                        id = self.ColNames.index(pos[1:])
                        znak = -1
                    else:
                        id = self.ColNames.index(pos)
                        znak = 1
                    ts.append((id, znak))
            tab.sort(cmp=lambda x, y: str_cmp(x, y, ts))
        return tab

    def count(self, value):
        key = 'FOLDER_' + b32encode(self.Folder.encode('utf-8')).decode('utf-8') + '_COUNT'
        countvalue = cache.get(key + '::' + is_null(value, ''))
# countvalue = None
        if countvalue:
            return countvalue
        else:
            countvalue = len(self._get_table(value))
            cache.set(key + '::' + is_null(value, ''), countvalue, 300)
            return countvalue
        return len(self._get_table(value))

    def insert_rec(self, rec):
        pass

    def update_rec(self, rec):
        pass

    def delete_rec(self, nr):
        pass

    def auto(
        self,
        col_name,
        col_names,
        rec,
        ):
        pass

    def exec_command(self, value):
        """format pliku exec:
        COPY(source_folder, dest_folder, files, mask);
        DEL(source_folder, files);
        MKDIR(source_folder, folder_name);
        MOVE(source_folder, dest_folder, files, mask):
        RENAME(source_folder, old_name, new_name);

"""

        thread_commands = ('COPY', 'MOVE', 'DELETE')
        if value[0] in thread_commands:
            pass
        elif value[0] == 'MKDIR':
            path = b32decode(value[2][0])
            name = b32decode(value[2][1])
            f = get_dir(path, vfsman)
            f.mk_dir(name)
            c = {}
        elif value[0] == 'RENAME':
            oldname = b32decode(value[1][0]).split('/')[-1]
            path = b32decode(value[2][0])
            name = b32decode(value[2][1])
            f = get_dir(path, vfsman)
            f.rename(oldname, name)
            c = {}
        else:
            #global scr
            #thread_name = schthread.ThreadSerwerStartApp('kosmos',
            #        'schlib.schfs.vfstable:TestThread', type=1)
            #c = {'thread': thread_name}
            pass
        return c


def vfstable_view(request, folder, value=None):
    if request.POST:
        p = request.POST.copy()
        d = {}
        for (key, val) in list(p.items()):
            if key != 'csrfmiddlewaretoken':
                d[str(key)] = schjson.loads(val)
    else:
        d = {}
    if value and value != '' and value != '_':
        d['value'] = b32decode(value.encode('utf-8')).decode('utf-8')
    if folder and folder != '' and folder != '_':
        folder2 = b32decode(folder.encode('utf-8')).decode('utf-8')
    else:
        folder2 = '/'
    folder2 = replace_dot(folder2)
    tabview = VfsTable(folder2)
    retstr = tabview.command(d)
    return HttpResponse(retstr)


def vfsopen(request, file):
    try:
        try:
            file2 = b32decode(file).decode('utf-8')
        except:
            file2 = b32decode(file.encode('utf-8')).decode('utf-8')
        plik = open_file(file2, vfsman)
        buf = plik.read()
        plik.close()
    except:
        buf = ''
    return HttpResponse(buf)


def vfsopen_page(request, file, page):
    try:
        file2 = b32decode(file).decode('utf-8')
        page2 = int(page)
        plik = open_file(file2, vfsman)
        try:
            plik.seek(page2 * 4096)
            buf = plik.read(4096).encode('hex')
            plik.close()
        except:
# print sys.exc_info()[0] print sys.exc_info() traceback.print_exc()
            buf = ''
    except:
        buf = ''
    return HttpResponse(buf)


def vfssave(request, file):
    buf = 'ERROR'
    plik = None
# print "save0"
    if request.POST:
# print "save1"
        try:
            data = request.POST['data']
# print "save2"
            file2 = b32decode(file).decode('utf-8')
# print "save3", file2
            plik = OpenFile(file2, vfsman)
# print "save4"
            plik.write(data)
# print "save5"
            plik.close()
# print "save6"
            buf = 'OK'
        except:
            buf = 'ERROR: ' + str(sys.exc_info()[0])
            if plik:
                plik.close()
    return HttpResponse(buf)


